package com.guchenbo.schedule;

import java.util.Date;
import jakarta.annotation.Resource;
import org.quartz.CronScheduleBuilder;
import org.quartz.CronTrigger;
import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.JobKey;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.Trigger;
import org.quartz.TriggerBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

/**
 * @author guchenbo
 */
@Component
public class DemoQuartzScheduler {
    protected static final Logger log = LoggerFactory.getLogger(DemoQuartzScheduler.class);

    public static final String GROUP_NAME = "demo";

    @Resource
    private Scheduler scheduler;

    public void startJob(String jobName, String cron, Date expireDate) throws SchedulerException {
        Class<DemoQuartzJob> jobClass = DemoQuartzJob.class;
        JobDetail jobDetail = JobBuilder.newJob(jobClass).withIdentity(jobName, GROUP_NAME).build();
        Trigger trigger = buildTrigger(jobName, GROUP_NAME, cron, expireDate);
        log.info("start job {}-{}-{}, cron {}", jobName, GROUP_NAME, jobClass.getSimpleName(), cron);
        scheduler.scheduleJob(jobDetail, trigger);
        scheduler.start();
    }

    public void deleteJob(String jobName) {
        JobKey jobKey = null;
        try {
            jobKey = JobKey.jobKey(jobName, GROUP_NAME);
            JobDetail jobDetail = scheduler.getJobDetail(jobKey);
            if (jobDetail == null) {
                log.warn("未找到对应的quartz任务, jobName={}", jobName);
                return;
            }
            scheduler.deleteJob(jobKey);
        } catch (Exception e) {
            log.error("delete job error {}", jobKey, e);
        }
        log.info("delete job MONITOR_TEMPLATE_MARK, jobKey= {}", jobKey);
    }

    private Trigger buildTrigger(String jobName, String groupName, String cron, Date expireDate) {
        CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(cron);
        TriggerBuilder<CronTrigger> builder = TriggerBuilder.newTrigger().withIdentity(jobName, groupName)
                        .withSchedule(scheduleBuilder);
        if (null != expireDate) {
            builder = builder.endAt(expireDate);
        }
        return builder.build();
    }
}
